<?php
// +----------------------------------------------------------------------
// | 作品操作区
// +----------------------------------------------------------------------

namespace User\Controller;
use Common\Controller\Base;
use Common\Model\Model;
use Think\Controller;

class BakeController extends UserbaseController {

    /**
     * 添加作品
     */
    public function worksadd(){
        if (IS_POST) {
            //栏目ID
            $cateid = intval($_POST['cateid']);
            $post=$_POST;
            $post['title'] = trim($post['title']);
            unset($post['file']);
            $post['image'] = $post['all_pic'][0];
            $arr = array();
            foreach($post['all_pic'] as $k => $v)
            {
            	if($k == 0 || !empty($v))
            	{
            		$arr[] = $v;
            	}
            }
            $post['all_pic'] = json_encode($arr);
            $post['type']=1;
            $post['userid']=$this->userid;
            
            //获取当前栏目配置
            $category = getCategory($cateid);
            $model=D('User/Works');
            if ($category['child'] == 0) {
                $status = $model->addModel($post);
                if ($status) {
                    $this->success("作品添加成功！",U('/user/index/works?st=0'));
                } else {
                    $error = $model->getError();
                    $this->error($error ? $error : '添加失败！');
                }
            } else {
                $this->error("该栏目类型无法发布！");
            }
        }else{
            $this->assign("category", $this->getcategory_tree($this->cateid));
            $this->display();
        }

    }

    //保存草稿
    public function workstempadd()
    {  
    	$cateid = intval($_POST['cateid']);
        $post=$_POST;
        unset($post['file']);
        $post['image'] = $post['all_pic'][0];
        $arr = array();
        foreach($post['all_pic'] as $k => $v)
        {
            if($k == 0 || !empty($v))
            {
            	$arr[] = $v;
            }
        }
        $post['all_pic'] = json_encode($arr);
        $post['type']=1;
        $post['userid']=$this->userid;
        $post['modify_time'] = '';
        
         //获取当前栏目配置
        $category = getCategory($cateid);
        $model=D('User/Works');
        if ($category['child'] == 0) {
           
        	$status = $model->addtempModel($post);
           
            if ($status) {
                $this->success("作品成功保存到草稿箱！",U('/user/index/works?st=5'));
            } else {
                $error = $model->getError();
                $this->error($error ? $error : '保存到草稿箱失败！');
            }
        } else {
            $this->error("该栏目类型无法发布！");
        }
    }

    //作品编辑
    public function worksedit(){
        if(IS_POST){
            $data=$_POST;
            $temp_status = $_POST['status'];
            unset($data['status']);
            $data['image'] = $data['all_pic'][0];
            $arr = array();
            foreach($data['all_pic'] as $k => $v)
            {
            	if($k == 0 || !empty($v))
            	{
            		$arr[] = $v;
            	}
            }
            unset($data['file']);
            $data['all_pic'] = json_encode($arr);
            $data['status']= 0;
            $data['userid']=$this->userid;
            $data['modify_time'] = '';
            
            $count=M('Works')->where(array('userid'=>$this->userid,'workid'=>$data['workid']))->count();
            if($count<1){
            	if(temp_status == 5)
            	{
            		$this->error('您无权发布该作品信息!');
            	}
            	else
            	{
                	$this->error('您无权更新该作品信息!');
            	}
            }
            $model=D('User/Works');
            $status = $model->editModel($data);
            if ($status) {
            	if(temp_status == 5)
            	{
            		$this->success("作品发布成功！",U('/user/index/works?st=0'));
            	}
            	else 
            	{
                	$this->success("作品更新成功！",U('/user/index/works?st=0'));
            	}
            } else {
                $error = $model->getError();
                if(temp_status == 5)
                {
                	$this->error($error ? $error : '发布失败！');
                }
                else
                {
                	$this->error($error ? $error : '更新失败！');
                }
            }
        }else{
            $workid=I('get.wid');
            $data=D('User/Works')->relation(true)->where(array('userid'=>$this->userid,'workid'=>$workid))->find();
            if($data){
            	if(!empty($data['all_pic']))
            	{
            		$all_pic = json_decode($data['all_pic'], true);
            		$data['all_pic'] = $all_pic;
            	}
            	else
            	{
            		$data['all_pic'][] = $data['image'];
            	}
                $this->assign("category", $this->getcategory_tree($data['cateid']));
                $this->assign('data',$data);
            }else{
                $this->error('您访问的页面不存在!');
            }
            $this->display();
        }
    }
    
    //编辑保存为草稿
    public function workstempedit()
    {
    	$data=$_POST;
    	$data['image'] = $data['all_pic'][0];
    	$arr = array();
    	foreach($data['all_pic'] as $k => $v)
    	{
    		if($k == 0 || !empty($v))
    		{
    			$arr[] = $v;
    		}
    	}
    	unset($data['file']);
    	$data['all_pic'] = json_encode($arr);
    	$data['status']= 5;
    	$data['userid']=$this->userid;
    	$data['modify_time'] = '';
        
    	$count=M('Works')->where(array('userid'=>$this->userid,'workid'=>$data['workid']))->count();
    	if($count<1){
    		$this->error('您无权更新该作品草稿信息!');
    	}
    	$model=D('User/Works');
    	$status = $model->edittempModel($data);
    	if ($status) {
    		$this->success("草稿更新成功！",U('/user/index/works?st=5'));
    	} else {
    		$error = $model->getError();
    		$this->error($error ? $error : '更新失败！');
    	}
    }

    //删除原料
    public function delworkMT(){
        $id=I('get.id');
        if(empty($id)){
            $this->error('删除信息出错!');
        }
        $workid=M('WorksMaterials')->where(array('id'=>$id))->getField('workid');
        if(M('WorksMaterials')->where(array('workid'=>$workid))->count()<2){
            //$this->error('至少要一个制作原料');
        }
        $model=new Model();
        $result=$model->table(array(
            C('DB_PREFIX').'works_materials'=>'M',
            C('DB_PREFIX').'works'=>'W',
        ))
            ->where('W.userid='.$this->userid.' and M.workid=W.workid and M.id='.$id)
            ->count();

        if($result){
            if(M('WorksMaterials')->where(array('id'=>$id))->delete()){
                $this->success('删除成功');
            }else{
                $this->error('删除失败!');
            }
        }else{
            $this->error('您无权删除此作品信息!');
        }
    }

    //删除步骤
    public function delworkST(){
        $id=I('get.id');
        if(empty($id)){
            $this->error('删除信息出错!');
        }
        $model=new Model();
        $result=$model->table(array(
            C('DB_PREFIX').'works_makestep'=>'M',
            C('DB_PREFIX').'works'=>'W',
        ))
            ->where('W.userid='.$this->userid.' and M.workid=W.workid and M.id='.$id)
            ->count();

        if($result){
            if(M('WorksMakestep')->where(array('id'=>$id))->delete()){
                $this->success('删除成功');
            }else{
                $this->error('删除失败!');
            }
        }else{
            $this->error('您无权删除此作品信息!');
        }
    }

    /*
     * 发布随手拍作品
     */
    public function suipaiadd(){
        if (IS_POST) {
            //栏目ID
            $arr = array();
        	$data['title'] = $_POST['title'];
        	$data['image'] = $_POST['all_pic'][0];
        	
        	foreach($_POST['all_pic'] as $k => $v)
        	{
        		if($k == 0 || !empty($v))
        		{
        			$arr[] = $v;
        		}
        	}
        	$data['all_pic'] = json_encode($arr);
        	$data['content'] = $_POST['content'];
            $post=$data;
            $post['userid']=$this->userid;
            $model=D('User/Works');
            $status = $model->suipaiAddModel($post);
            if ($status) {
                //随手拍活动
                if(!empty($post['addtype'])){
                    $datas['userid']=$this->userid;
                    $datas['workid']=$status;
                    $datas['create_time']=time();
                    $datas['ifwin']=false;
                    M('ToppicSuipai')->add($datas);
                    $this->success("作品添加成功,请等待审核！",U('/toppic/suipai/show'));
                }

                //更新随拍作品数
           //     service('Passport')->userDynamic($this->userid,0, '做过'.$post['title'],1,'spadd');
                $this->success("作品添加成功,请等待审核！",U('/user/index/suipai?st=0'));
            } else {
                $error = $model->getError();
                $this->error($error ? $error : '添加失败！');
            }
        }
        else{
            $this->display();
        }
    }

    //随拍作品编辑
    public function suipaiedit(){
        if(IS_POST){
        	$post['title'] = $_POST['title'];
        	$post['content'] = $_POST['content'];
        	$arr = array();
        	$post['image'] = $_POST['all_pic'][0];
        	
        	foreach($_POST['all_pic'] as $k => $v)
        	{
        		if($k == 0 || !empty($v))
        		{
        			$arr[] = $v;
        		}
        	}
        	$post['id'] = $_POST['id'];
        	$post['all_pic'] = json_encode($arr);
        	$post['modify_time'] = '';
            $data=$post;
            $data['userid']=$this->userid;
            $count=M('Suipai')->where(array('userid'=>$this->userid,'id'=>$data['id']))->count();
            if($count<1){
                $this->error('您无权更新该作品信息!');
            }
            $model=D('User/Works');
            $status = $model->suipaiEditModel($data);
            if ($status) {
                $this->success("作品更新成功！",U('/user/index/suipai?st=0'));
            } else {
                $error = $model->getError();
                $this->error($error ? $error : '更新失败！');
            }
        }else{
            $workid=I('get.id');
            $data=M('Suipai')->where(array('userid'=>$this->userid,'id'=>$workid))->find();
            if($data){
            	if(!empty($data['all_pic']))
            	{
            		$all_pic = json_decode($data['all_pic'], true);
            		$data['all_pic'] = $all_pic;
            	}
            	else 
            	{
            		$data['all_pic'][] = $data['image'];
            	}
                $this->assign('data',$data);
            }else{
                $this->error('您访问的页面不存在!');
            }
            $this->display();
        }
    }

    /*
     * 发布COPY作品
     */
    public function copyadd(){
        if (IS_POST) {
            //栏目ID
            $copyid = I('post.copyid');
            if(empty($copyid)){
                $this->error('页面访问出错,请稍候再试!');
            }
            $works=M('Works')->field('title,cateid')->where(array('workid'=>$copyid))->find();
            $cateid=$works['cateid'];
            $post=$_POST;
            $post['type']=2;
            $post['userid']=$this->userid;
            $post['cateid']=$cateid;
            if(empty($post['image']))
            {
            	$this->error("请上传作品图片");
            }
            if(empty($post['content']))
            {
            	$this->error("请填写作品简介");
            }
            $model=D('User/Works');
            $status = $model->copyAddModel($post);
            if ($status) {
                //更新随拍作品数
                M('Works')->where(array('workid'=>$copyid))->setInc('copynum',1);
             //   service('Passport')->userDynamic($this->userid,0, '做过'.$post['title'],1,'workadd');
                $this->success("作品添加成功！",U('/user/index/copy?st=0'));
            } else {
                $error = $model->getError();
                $this->error($error ? $error : '添加失败！');
            }
        }
        else{
            $copyid=!empty($_GET['wid'])?$_GET['wid']:'';
            $this->worktitle=M('Works')->where(array('workid'=>$copyid))->getField('title');
            $this->assign("copyid", $copyid);
            $this->assign("category", $this->getcategory_tree($this->cateid));
            $this->display();
        }
    }

    //参考作品编辑
    public function copyedit(){
        if(IS_POST){
            $data=$_POST;
            $data['userid']=$this->userid;
            $count=M('Works')->where(array('userid'=>$this->userid,'workid'=>$data['workid']))->count();
            if($count<1){
                $this->error('您无权更新该作品信息!');
            }
            if(empty($data['image']))
            {
            	$this->error("请上传作品图片");
            }
            if(empty($data['content']))
            {
            	$this->error("请填写作品简介");
            }
            $model=D('User/Works');
            $status = $model->copyEditModel($data);
            if ($status) {
                $this->success("作品更新成功！",U('/user/index/copy?st=0'));
            } else {
                $error = $model->getError();
                $this->error($error ? $error : '更新失败！');
            }
        }else{
            $workid=I('get.wid');
            $data=M('Works')->where(array('userid'=>$this->userid,'workid'=>$workid))->find();
            if($data){
                $this->assign('data',$data);
            }else{
                $this->error('您访问的页面不存在!');
            }
            $this->display();
        }
    }


    //获取栏目
    public function getcategory_tree($cateid){

        $tree = new \Tree();
        $tree->icon = array('&nbsp;&nbsp;│ ', '&nbsp;&nbsp;├─ ', '&nbsp;&nbsp;└─ ');
        $tree->nbsp = '&nbsp;&nbsp;';
        $categorys = array();
        $categorysList=cache('Category');
        if(empty($categorysList)){
            $categorysList=D('User/Works')->getCategoryData();
        }else{
            $categorysList=cache('Category');
        }
        foreach ($categorysList as $cid => $r) {
            $r = getCategory($r['cateid']);
            $r['disabled'] = $r['child'] ? 'disabled' : '';
            $r['selected'] = $cid == $cateid ? 'selected' : '';
            $categorys[$cid] = $r;
        }
        $str = "<option value='\$cateid' \$selected \$disabled>\$spacer \$catename</option>";
        $tree->init($categorys);
        $string .= $tree->get_tree(0, $str);

        return $string;
    }




}